package com.jeeplus.itemInterface.groupInterface;

import com.alibaba.fastjson.JSON;
import com.github.wxpay.sdk.WXPayUtil;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.address.entity.Address;
import com.jeeplus.modules.address.service.AddressService;
import com.jeeplus.modules.dynamicrecord.entity.DynamicRecord;
import com.jeeplus.modules.dynamicrecord.service.DynamicRecordService;
import com.jeeplus.modules.grouporders.entity.GroupOrders;
import com.jeeplus.modules.grouporders.service.GroupOrdersService;
import com.jeeplus.modules.grouprecord.entity.GroupRecord;
import com.jeeplus.modules.grouprecord.service.GroupRecordService;
import com.jeeplus.modules.groupreturn.entity.GroupReturn;
import com.jeeplus.modules.groupreturn.mapper.GroupReturnMapper;
import com.jeeplus.modules.groupreturn.service.GroupReturnService;
import com.jeeplus.modules.member.entity.Member;
import com.jeeplus.modules.member.service.MemberService;
import com.jeeplus.modules.ordersstore.entity.BalanceOrder;
import com.jeeplus.modules.ordersstore.entity.OrdersStore;
import com.jeeplus.modules.ordersstore.service.OrdersStoreService;
import com.jeeplus.modules.partitioninfo.entity.PartitionInfo;
import com.jeeplus.modules.partitioninfo.service.PartitionInfoService;
import com.jeeplus.modules.recharge.entity.BalanceDetail;
import com.jeeplus.modules.recharge.entity.Recharge;
import com.jeeplus.modules.recharge.service.RechargeService;
import com.jeeplus.modules.sessions.entity.Sessions;
import com.jeeplus.modules.sessions.service.SessionsService;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.tixian.entity.Tixian;
import com.jeeplus.modules.tixian.service.TixianService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Api(value = "GroupsInterfaceController",description = "拼团接口")
@Controller
@RequestMapping(value = "${frontPath}/group")
public class GroupsInterfaceController {

    private org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private SessionsService sessionsService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private PartitionInfoService partitionInfoService;
    @Autowired
    private GroupOrdersService groupOrdersService;
    @Autowired
    private GroupRecordService groupRecordService;
    @Autowired
    private GroupReturnService groupReturnService;
    @Autowired
    private DynamicRecordService dynamicRecordService;
    @Autowired
    private TixianService tixianService;
    @Autowired
    private RechargeService rechargeService;
    @Autowired
    private OrdersStoreService ordersStoreService;
    @Autowired
    private AddressService addressService;

    private final static String APPID = "wxf8333f0015bfad41";
    private final static String APPSECRET = "8104ad1318a445ace1bf2eb604330783";
    private final static String MCH_ID = "1607079032";
    private final static String PATERNERKEY = "yizhelegouyizhelegou111111686868";

    @ApiOperation(value = "获取拼团分区",notes = "获取拼团分区")
    @GetMapping("/getGroups")
    @ResponseBody
    public AjaxJson getGroups(){
        AjaxJson aj = new AjaxJson();
        //查询拼团抽奖分区列表
        List<Sessions> sessionsList = sessionsService.findAllList(new Sessions());
        aj.put("sessionsList",sessionsList);
        aj.setSuccess(true);
        return aj;
    }

    @ApiOperation(value = "进入指定分区",notes = "进入指定分区")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sessionsId",value = "分区id",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "memberId",value = "用户id",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping("/goToTheGroup")
    @ResponseBody
    public AjaxJson goToTheGroup(String sessionsId,String memberId){
        AjaxJson aj = new AjaxJson();
        //查询用户
        Member member = memberService.get(memberId);
        int num = 0;
        if (member != null){
            //查询拼团抽奖分区详情
            Sessions sessions = sessionsService.get(sessionsId);
            if (sessions != null){
                //判断是否是该场次拼团时间段
                try {
                    SimpleDateFormat df = new SimpleDateFormat("HH:mm");//设置日期格式
                    Date nowTime =df.parse(df.format(new Date()));
                    //规定时间
                    Date beginTime = df.parse(sessions.getSessionsBegin());
                    Date endTime = df.parse(sessions.getSessionsEnd());
                    //调用判断方法是否在规定时间段内
                    boolean isTime = DateUtils.timeCalendar(nowTime, beginTime, endTime);
                    if (!isTime){
                        aj.setSuccess(false);
                        aj.setMsg("该分区拼团开放时间为"+sessions.getSessionsBegin()+"至"+sessions.getSessionsEnd());
                        return aj;
                    }
                }catch (ParseException e){
                    e.printStackTrace();
                }
                //参团人数
                GroupRecord newGroup = groupRecordService.findNewGroup(sessionsId);
                if (newGroup != null){
                    GroupOrders groupOrders = new GroupOrders();
                    groupOrders.setSessions(sessions);
                    groupOrders.setGroupRecord(newGroup);
                    List<GroupOrders> list1 = groupOrdersService.findList(groupOrders);
                    num = list1.size();
                }
                aj.put("sessions",sessions);
                aj.put("num",num);
                aj.setSuccess(true);
            }else {
                aj.setSuccess(false);
                aj.setMsg("分区信息有误");
            }
        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
        }

        return aj;
    }



    @ApiOperation(value = "参与拼团",notes = "参与拼团")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sessionsId",value = "分区id",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "memberId",value = "用户id",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "method",value = "支付方式（0余额1微信）",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "openid",value = "openid",required = false,dataType = "String",paramType = "query")
    })
    @PostMapping("/conductGroup")
    @ResponseBody
    public AjaxJson conductGroup(String sessionsId,String memberId,String recordId,String method,String openid,HttpServletRequest request,HttpServletResponse response){
        AjaxJson aj = new AjaxJson();
        //查询用户
        Member member = memberService.get(memberId);
        if (member != null){
            System.out.println("=============================================openid:"+openid);
            //查询拼团抽奖分区详情
            Sessions sessions = sessionsService.get(sessionsId);
            if (sessions != null) {
                //判断是否是该场次拼团时间段
                try {
                    SimpleDateFormat df = new SimpleDateFormat("HH:mm");//设置日期格式
                    Date nowTime = df.parse(df.format(new Date()));
                    //规定时间
                    Date beginTime = df.parse(sessions.getSessionsBegin());
                    Date endTime = df.parse(sessions.getSessionsEnd());
                    //调用判断方法是否在规定时间段内
                    boolean isTime = DateUtils.timeCalendar(nowTime, beginTime, endTime);
                    if (!isTime) {
                        aj.setSuccess(false);
                        aj.setMsg("该分区拼团开放时间为" + sessions.getSessionsBegin() + "至" + sessions.getSessionsEnd());
                        return aj;
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                //判断用户对应场次的能量值是否为0
                PartitionInfo partitionInfo = new PartitionInfo();
                partitionInfo.setMember(member);
                partitionInfo.setSessions(sessions);
                List<PartitionInfo> list = partitionInfoService.findList(partitionInfo);
                if (list.size() > 0) {
                    if (list.get(0).getEnergyValue() <= 0) {
                        aj.setSuccess(false);
                        aj.setMsg("您的能量值已空，请明日再来参加！");
                        return aj;
                    }
                }
            }

            //加锁，限制用户排队参加拼团
            Jedis jedis = new Jedis("localhost",6379);
            Long result = jedis.setnx("my_group",memberId);
            if (result == 1){
                //设置有效期10秒
                jedis.expire("my_group",10);
                aj = groupOrdersService.participateInTheCompetition(sessionsId,member,recordId,method,openid,request,response);
                jedis.del("my_group");
            }else {
                aj.setSuccess(false);
                aj.setMsg("当前参与人数过多，请重试！");
                return aj;
            }
        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
        }

        return aj;
    }




    @ApiOperation(value = "拼团订单列表",notes = "拼团订单列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "memberId",value = "用户id",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "groupFlag",value = "拼团标识（0:参团中 1:参团成功）",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "prizeFlag",value = "中奖标识（0:全部 1:中奖 2:未中奖 3:已退还）",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping("/getOrderList")
    @ResponseBody
    public AjaxJson getOrderList(String memberId,String groupFlag,String prizeFlag){
        AjaxJson aj = new AjaxJson();
        //查询用户
        Member member = memberService.get(memberId);
        List<GroupOrders> ordersList = new ArrayList<>();
        if (member != null){
            if ("0".equals(groupFlag)){
                //参团中未开奖
                GroupOrders groupOrders = new GroupOrders();
                groupOrders.setMember(member);
                groupOrders.setOrderStatus("0");
                List<GroupOrders> list = groupOrdersService.findList(groupOrders);
                for (GroupOrders orders : list) {
                    orders.setBoughtTime(DateUtils.formatDateTime(orders.getCreateDate()));
                }
                ordersList.addAll(list);
            } else if ("1".equals(groupFlag)){
                if ("0".equals(prizeFlag)){
                    //全部拼团成功的
                    GroupOrders groupOrders = new GroupOrders();
                    groupOrders.setMember(member);
                    groupOrders.setOrderStatus("1");
                    List<GroupOrders> list = groupOrdersService.findList(groupOrders);
                    if (list.size()>0){
                        for (GroupOrders orders : list) {
                            orders.setBoughtTime(DateUtils.formatDateTime(orders.getCreateDate()));
                            if ("0".equals(orders.getPrizeFlag())){
                                //未中奖
                                orders.setgStatus("0");
                            }else if ("1".equals(orders.getPrizeFlag())){
                                //中奖
                                orders.setgStatus("1");
                            }
                        }
                        ordersList.addAll(list);
                    }

                    groupOrders.setOrderStatus("2");
                    List<GroupOrders> list1 = groupOrdersService.findList(groupOrders);
                    if (list1.size()>0){
                        for (GroupOrders orders : list1) {
                            orders.setBoughtTime(DateUtils.formatDateTime(orders.getCreateDate()));
                            //返还
                            orders.setgStatus("2");
                        }
                        ordersList.addAll(list1);
                    }

                    groupOrders.setOrderStatus("3");
                    List<GroupOrders> list2 = groupOrdersService.findList(groupOrders);
                    if (list2.size()>0){
                        for (GroupOrders orders : list2) {
                            orders.setBoughtTime(DateUtils.formatDateTime(orders.getCreateDate()));
                            //已发货    中奖
                            orders.setgStatus("1");
                        }
                        ordersList.addAll(list2);
                    }
                    ordersList = ordersList.stream().sorted(Comparator.comparing(GroupOrders::getCreateDate).reversed()).collect(Collectors.toList());
                }else if ("1".equals(prizeFlag)){
                    //中奖
                    GroupOrders groupOrders = new GroupOrders();
                    groupOrders.setMember(member);
//                    groupOrders.setOrderStatus("1");
                    groupOrders.setPrizeFlag("1");
                    List<GroupOrders> list = groupOrdersService.findList(groupOrders);
                    for (GroupOrders orders : list) {
                        orders.setBoughtTime(DateUtils.formatDateTime(orders.getCreateDate()));
                    }
                    ordersList.addAll(list);
                }else if ("2".equals(prizeFlag)){
                    //未中奖
                    GroupOrders groupOrders = new GroupOrders();
                    groupOrders.setMember(member);
                    groupOrders.setOrderStatus("1");
                    groupOrders.setPrizeFlag("0");
                    List<GroupOrders> list = groupOrdersService.findList(groupOrders);
                    for (GroupOrders orders : list) {
                        orders.setBoughtTime(DateUtils.formatDateTime(orders.getCreateDate()));
                    }
                    ordersList.addAll(list);
                }else if ("3".equals(prizeFlag)){
                    //已退还
                    GroupOrders groupOrders = new GroupOrders();
                    groupOrders.setMember(member);
                    groupOrders.setOrderStatus("2");
                    List<GroupOrders> list = groupOrdersService.findList(groupOrders);
                    for (GroupOrders orders : list) {
                        orders.setBoughtTime(DateUtils.formatDateTime(orders.getCreateDate()));
                    }
                    ordersList.addAll(list);
                }
            }
            if (ordersList.size()>0){
                for (GroupOrders groupOrders : ordersList) {
                    GroupRecord groupRecord = groupRecordService.get(groupOrders.getGroupRecord().getId());
                    Sessions sessions = sessionsService.get(groupRecord.getSessions().getId());
                    groupOrders.setSessions(sessions);
                }
            }
        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
        }
        aj.setSuccess(true);
        aj.put("ordersList",ordersList);
        return aj;
    }

    @ApiOperation(value = "拼团订单详情",notes = "拼团订单详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "memberId",value = "用户id",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "orderNo",value = "订单编号",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping("/getOrderDetail")
    @ResponseBody
    public AjaxJson getOrderDetail(String memberId,String orderNo){
        AjaxJson aj = new AjaxJson();
        //查询用户
        Member member = memberService.get(memberId);
        if (member != null){
            GroupOrders groupOrders = new GroupOrders();
            groupOrders.setMember(member);
            groupOrders.setOrderNo(orderNo);
            List<GroupOrders> list = groupOrdersService.findList(groupOrders);
            if (list.size()>0){
                for (GroupOrders orders : list) {
                    GroupRecord groupRecord = groupRecordService.get(orders.getGroupRecord().getId());
                    Sessions sessions = sessionsService.get(groupRecord.getSessions().getId());
                    orders.setSessions(sessions);
                    //没中奖的  已返还金额
                    if ("0".equals(orders.getPrizeFlag())){
                        GroupReturn groupReturn = new GroupReturn();
                        groupReturn.setOrderNo(orders.getOrderNo());
                        groupReturn.setMember(member);
                        List<GroupReturn> returnList = groupReturnService.findList(groupReturn);
                        orders.setReturnMoney(returnList.get(0).getMoney());
                    }
                }
                aj.put("order",list.get(0));
            }else {
                aj.setSuccess(false);
                aj.setMsg("订单信息有误");
            }
        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
        }
        aj.setSuccess(true);
        return aj;
    }


    @ApiOperation(value = "查看幸运星收益信息",notes = "查看幸运星收益信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "memberId",value = "用户id",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping("/getStarInfo")
    @ResponseBody
    public AjaxJson getStarInfo(String memberId){
        AjaxJson aj = new AjaxJson();
        //查询用户
        Member member = memberService.get(memberId);
        if (member != null){
            PartitionInfo partitionInfo = new PartitionInfo();
            partitionInfo.setMember(member);
            List<PartitionInfo> partitionInfoList = partitionInfoService.findList(partitionInfo);
            for (PartitionInfo info : partitionInfoList) {
                Sessions sessions = sessionsService.get(info.getSessions().getId());
                info.setSessions(sessions);
                info.setSelectTime(DateUtils.formatDateTime(sessions.getCreateDate()));
            }
            partitionInfoList = partitionInfoList.stream().sorted(Comparator.comparing(PartitionInfo::getSelectTime)).collect(Collectors.toList());
            DynamicRecord dynamicRecord = new DynamicRecord();
            dynamicRecord.setMember(member);
            dynamicRecord.setName("幸运收益");
            List<DynamicRecord> list = dynamicRecordService.findList(dynamicRecord);
            for (DynamicRecord record : list) {
                Sessions sessions = sessionsService.get(record.getRemarks());
                record.setSessions(sessions);
            }
            BigDecimal sumMoney = BigDecimal.valueOf(list.stream().mapToDouble(DynamicRecord::getMoney).sum());
            aj.put("partitionInfoList",partitionInfoList);
            aj.put("dynamicRecordList",list);
            aj.put("sumMoney",sumMoney);
        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
        }
        aj.setSuccess(true);
        return aj;
    }


    @ApiOperation(value = "查看拼团奖明细",notes = "查看拼团奖明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "memberId",value = "用户id",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping("/getGroupProfitInfo")
    @ResponseBody
    public AjaxJson getGroupProfitInfo(String memberId){
        AjaxJson aj = new AjaxJson();
        //查询用户
        Member member = memberService.get(memberId);
        List<GroupReturn> returnList = new ArrayList<>();
        if (member != null){
            GroupOrders groupOrders = new GroupOrders();
            groupOrders.setMember(member);
            groupOrders.setPrizeFlag("0");
            List<GroupOrders> list = groupOrdersService.findList(groupOrders);
            if (list.size()>0){
                for (GroupOrders orders : list) {
                    GroupReturn groupReturn = new GroupReturn();
                    groupReturn.setMember(member);
                    groupReturn.setOrderNo(orders.getOrderNo());
                    List<GroupReturn> list1 = groupReturnService.findList(groupReturn);
                    if (list1.size()>0){
                        Sessions sessions = sessionsService.get(list1.get(0).getId());
                        list1.get(0).setSessions(sessions);
//                        list1.get(0).setMoney(list1.get(0).getMoney()-orders.getMoney());
                        list1.get(0).setMoney(list1.get(0).getMoney());
                        list1.get(0).setReturnTime(DateUtils.formatDateTime(list1.get(0).getCreateDate()));
                        returnList.add(list1.get(0));
                    }
                }
                returnList = returnList.stream().sorted(Comparator.comparing(GroupReturn::getCreateDate).reversed()).collect(Collectors.toList());
            }
        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
        }
        aj.setSuccess(true);
        aj.put("returnList",returnList);
        return aj;
    }


    @ApiOperation(value = "拼团明细",notes = "拼团明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "memberId",value = "用户id",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping("/getGroupInfo")
    @ResponseBody
    public AjaxJson getGroupInfo(String memberId){
        AjaxJson aj = new AjaxJson();
        //查询用户
        Member member = memberService.get(memberId);
        if (member != null){
            GroupOrders groupOrders = new GroupOrders();
            groupOrders.setMember(member);
            List<GroupOrders> list = groupOrdersService.findList(groupOrders);
            aj.put("list",list);
        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
        }
        aj.setSuccess(true);
        return aj;
    }



    @ApiOperation(value = "获取幸运星明细",notes = "获取幸运星明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "memberId",value = "用户id",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "sessionsId",value = "场次id",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping("/getWinningTimes")
    @ResponseBody
    public AjaxJson getWinningTimes(String memberId,String sessionsId){
        AjaxJson aj = new AjaxJson();
        //查询用户
        Member member = memberService.get(memberId);
        if (member != null){
            Sessions sessions = sessionsService.get(sessionsId);
            GroupRecord groupRecord = new GroupRecord();
            groupRecord.setMember(member);
            groupRecord.setSessions(sessions);
            List<GroupRecord> list = groupRecordService.findList(groupRecord);
            if (list.size()>0){
                for (GroupRecord record : list) {
                    record.setSessions(sessions);
                    record.setStarTime(DateUtils.formatDateTime(record.getCreateDate()));
                }
            }
            aj.put("list",list);
        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
        }
        aj.setSuccess(true);
        return aj;
    }


    @ApiOperation(value = "提现记录",notes = "提现记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "memberId",value = "用户id",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping("/getCashOutList")
    @ResponseBody
    public AjaxJson getCashOutList(String memberId){
        AjaxJson aj = new AjaxJson();
        //查询用户
        Member member = memberService.get(memberId);
        if (member != null){
            Tixian tixian = new Tixian();
            tixian.setMember(member);
            List<Tixian> list = tixianService.findList(tixian);
            if (list.size()>0){
                for (Tixian tixian1 : list) {
                    tixian1.setShenhe(DictUtils.getDictLabel(tixian1.getShenhe(),"shenhe",""));
                    tixian1.setCashTime(DateUtils.formatDateTime(tixian1.getCreateDate()));
                }
            }
            aj.put("list",list);
        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
        }
        aj.setSuccess(true);
        return aj;
    }



    @ApiOperation(value = "充值记录",notes = "充值记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "memberId",value = "用户id",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping("/getRechargeList")
    @ResponseBody
    public AjaxJson getRechargeList(String memberId){
        AjaxJson aj = new AjaxJson();
        //查询用户
        Member member = memberService.get(memberId);
        if (member != null){
            Recharge recharge = new Recharge();
            recharge.setMemberId(member.getId());
            List<Recharge> list = rechargeService.findList(recharge);
            if (list.size()>0){
                for (Recharge recharge1 : list) {
                    recharge1.setRechargeStatus(DictUtils.getDictLabel(recharge1.getRechargeStatus(),"shenhe",""));
                    recharge1.setExportTime(DateUtils.formatDateTime(recharge1.getCreateDate()));
                }
            }
            aj.put("list",list);
        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
        }
        aj.setSuccess(true);
        return aj;
    }


    @ApiOperation(value = "余额账单",notes = "余额账单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "memberId",value = "用户id",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping("/getBalanceInfo")
    @ResponseBody
    public AjaxJson getBalanceInfo(String memberId){
        AjaxJson aj = new AjaxJson();
        //查询用户
        Member member = memberService.get(memberId);
        List<BalanceOrder> balanceOrders = new ArrayList<>();
        if (member != null){
            //拼团
            GroupOrders groupOrders = new GroupOrders();
            groupOrders.setMember(member);
            List<GroupOrders> list = groupOrdersService.findList(groupOrders);
            if (list.size()>0){
                for (GroupOrders orders : list) {
                    BalanceOrder balanceOrder = new BalanceOrder();
                    balanceOrder.setMoney(orders.getMoney());
                    balanceOrder.setOrderNo(orders.getOrderNo());
                    GroupRecord groupRecord = groupRecordService.get(orders.getGroupRecord().getId());
                    Sessions sessions = sessionsService.get(groupRecord.getSessions().getId());
                    if (sessions != null){
                        balanceOrder.setSessionsName(sessions.getSessionsName());
                    }
                    balanceOrder.setTime(DateUtils.formatDateTime(orders.getCreateDate()));
                    if ("1".equals(orders.getOrderStatus())){
                        //拼团成功
                        balanceOrder.setType("0");
                        balanceOrders.add(balanceOrder);
                    }else if ("2".equals(orders.getOrderStatus())){
                        //拼团返还
                        balanceOrder.setType("1");
                        balanceOrders.add(balanceOrder);
                    }

                }
            }
            //正常商城
            OrdersStore ordersStore = new OrdersStore();
            ordersStore.setMember(member);
            List<OrdersStore> ordersStores = ordersStoreService.findList(ordersStore);
            if (ordersStores.size()>0){
                for (OrdersStore store : ordersStores) {
                    if (!"1".equals(store.getOrdersStatus()) && !"5".equals(store.getOrdersStatus())){
                        BalanceOrder balanceOrder = new BalanceOrder();
                        balanceOrder.setType("2");
                        balanceOrder.setTime(DateUtils.formatDateTime(store.getCreateDate()));
                        balanceOrder.setOrderNo(store.getOrdersNo());
                        balanceOrder.setMoney(store.getMoney());
                        balanceOrders.add(balanceOrder);
                    }
                }
            }
            if (balanceOrders.size()>0){
                balanceOrders = balanceOrders.stream().sorted(Comparator.comparing(BalanceOrder::getTime).reversed()).collect(Collectors.toList());
            }
            aj.put("balanceOrders",balanceOrders);
        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
        }
        aj.setSuccess(true);
        return aj;
    }


    @ApiOperation(value = "拼团奖记录",notes = "拼团奖记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "memberId",value = "用户id",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping("/getGroupPrizeList")
    @ResponseBody
    public AjaxJson getGroupPrizeList(String memberId){
        AjaxJson aj = new AjaxJson();
        //查询用户
        Member member = memberService.get(memberId);
        if (member != null){
            //活跃奖（团队奖）
            DynamicRecord dynamicRecord = new DynamicRecord();
            dynamicRecord.setMember(member);
            dynamicRecord.setName("团队奖");
            List<DynamicRecord> recordList = dynamicRecordService.findList(dynamicRecord);
            aj.put("list",recordList);
        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
        }
        aj.setSuccess(true);
        return aj;
    }


    @ApiOperation(value = "推荐奖记录",notes = "推荐奖记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "memberId",value = "用户id",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping("/getRecommendPrizeList")
    @ResponseBody
    public AjaxJson getRecommendPrizeList(String memberId){
        AjaxJson aj = new AjaxJson();
        //查询用户
        Member member = memberService.get(memberId);
        if (member != null){
            //推荐
            DynamicRecord dynamicRecord = new DynamicRecord();
            dynamicRecord.setMember(member);
            dynamicRecord.setName("推荐奖");
            List<DynamicRecord> recordList = dynamicRecordService.findList(dynamicRecord);
            aj.put("list",recordList);
        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
        }
        aj.setSuccess(true);
        return aj;
    }


    @ApiOperation(value = "返回openid",notes = "返回openid")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "memberId",value = "用户id",required = true,dataType = "String",paramType = "query")
    })
    @PostMapping("/sendOpenid")
    @ResponseBody
    public AjaxJson sendOpenid(String memberId){
        AjaxJson aj = new AjaxJson();
        //查询用户
        Member member = memberService.get(memberId);
        if (member != null){
            if (StringUtils.isNotBlank(member.getOpenid())){
                aj.setSuccess(true);
                aj.put("openid",member.getOpenid());
            }else {
                aj.setSuccess(false);
                aj.setMsg("用户信息有误");
            }
        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
        }
        return aj;
    }


    /**
     * to 发送GET请求
     *
     * @param requestUrl
     * @return
     */
    public static String getXpath(String requestUrl) {
        String res = "";
        JsonObject object = null;
        StringBuffer buffer = new StringBuffer();
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
            System.out.println(urlCon.getResponseCode());
            if (200 == urlCon.getResponseCode()) {
                InputStream is = urlCon.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, "utf-8");
                BufferedReader br = new BufferedReader(isr);
                String str = null;
                while ((str = br.readLine()) != null) {
                    buffer.append(str);
                }
                br.close();
                isr.close();
                is.close();
                res = buffer.toString().trim();
                JsonParser parse = new JsonParser();
                object = (JsonObject) parse.parse(res);
            } else {
                throw new Exception("连接失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object.toString();
    }


    @ResponseBody
    @GetMapping("getCode")
    public void getCode(HttpServletRequest request, HttpServletResponse response) throws Exception{
        System.out.println("===========================getCode===============================");
        String token = request.getParameter("token");
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf8333f0015bfad41&redirect_uri=http%3a%2f%2flgshangcheng.com%2fptw%2ff%2fgroup%2fgetOpenid&response_type=code&scope=snsapi_base&state="+token+"#wechat_redirect";
        response.sendRedirect(url);
    }


    @ResponseBody
    @GetMapping("getOpenid")
    public void getOpenid(HttpServletRequest request, HttpServletResponse response) throws Exception{
        System.out.println("****************************支付页获取openid*****************************");
        String openid = "";
        String code = request.getParameter("code");
        String token = request.getParameter("state");
        System.out.println("code===="+code);
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APPID + "&secret=" + APPSECRET
                + "&code=" + code + "&grant_type=authorization_code";
        String rtn = getXpath(url);
        System.out.println("rtn====="+rtn);
        if (!rtn.contains("errcode")) {
            openid = JSON.parseObject(rtn).getString("openid");

            //todo 插入用户表openid
            Member member = memberService.get(token);
            if (member != null){
                member.setOpenid(openid);
                memberService.save(member);
            }
            System.out.println("======================================更新用户openid成功！");
        }
        System.out.println("==========================================================openid="+openid);

        response.sendRedirect("http://lgshangcheng.com/#/pages/index/index");


    }


    /**
     * 微信支付回调
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/callBack")
    @ResponseBody
    public AjaxJson weChatCallBack(HttpServletRequest request, HttpServletResponse response){
        System.out.println("============================================支付回调========================================");
        AjaxJson aj = new AjaxJson();
        try{
            InputStream inputStream = request.getInputStream(); // 接收请求过来的流
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            StringBuffer stringBuffer = new StringBuffer();
            String line = "";
            while ((line = bufferedReader.readLine()) != null){
                stringBuffer.append(line);
            }
            Map<String, String> stringStringMap = WXPayUtil.xmlToMap(String.valueOf(stringBuffer)); // 将返回的xml转成Map集合
            String return_code = stringStringMap.get("return_code"); // 回调返回来的状态，根据自己需求做其他的业务
            String openid = stringStringMap.get("openid");
            String orderNumber = stringStringMap.get("out_trade_no");
            System.out.println("return_code="+return_code);
            System.out.println("openid="+openid);
            System.out.println("out_trade_no="+orderNumber);
            if ("SUCCESS".equals(return_code)){
                groupOrdersService.backGroup(openid,orderNumber);
            }
            System.out.println("回调成功==========="+stringBuffer.toString());

        }catch (Exception e){
            e.printStackTrace();
            aj.setSuccess(false);
            aj.setMsg("系统异常");
            System.out.println("系统异常=============");
        }

        return aj;
    }

}
